// base
import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
// less
import './index.less'
import { showToast } from '../../../crossplatform/apiservice/toast'
import If from '../if'

class ChooseList extends Component {
  inchooselist = index => {
    let inchoose = false
    this.props.chooselist.forEach(data => {
      if (data == index) {
        inchoose = true
      }
    })
    return inchoose
  }

  handleclick = index => {
    let { chooselist } = this.props
    const { dataWrap = {} } = this.props
    const { supportnum, type, datalist } = dataWrap
    const selectonly = datalist[index].selectonly
    const firstselectonly = datalist[0].selectonly // 为true时，第一个选了其他的都不能选；其他的都没选这个主动勾选
    if (chooselist && chooselist.length == 1) {
      let selectonlynow = datalist[chooselist[0]].selectonly
      if (selectonlynow) {
        chooselist = []
      }
    }
    let chooselistnew = []
    if (supportnum == 1) {
      chooselistnew = [index]
    } else if (selectonly) {
      chooselistnew = [index]
    } else {
      let inold = false
      chooselist.forEach(data => {
        if (data == index) {
          inold = true
        } else {
          chooselistnew.push(data)
        }
      })
      if (!inold) {
        chooselistnew.push(index)
      }
      if (chooselistnew.length > supportnum && supportnum != 'infinite') {
        showToast({
          title: `最多选择 ${supportnum} 个`
        })
        return
      }
    }
    if (firstselectonly && (!chooselistnew || !chooselistnew.length)) {
      // 如果第一个必选 且目前chooselistnew为空数组 将其至为第一个
      chooselistnew = [0]
    }
    this.props.onChooseChange({
      type: type,
      chooselist: chooselistnew
    })
  }

  delay (time = 0) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve()
      }, time)
    })
  }

  render () {
    const { dataWrap = {} } = this.props
    const { datalist = [] } = dataWrap
    return (
      <View className={`ChooseList_id46439 ${dataWrap.hide ? 'hide_list_choose' : ''}`}>
        <View className="choosepart-wrap">
          <View className="titlewrap">
            <View className="title">{dataWrap.title}</View>
            <View className="subtitle">{dataWrap.subtitle}</View>
          </View>
          <View className="listsinglewrap">
            {datalist.map((listsingle, index) => {
              return (
                <View
                  key={index}
                  onClick={this.handleclick.bind(this, index)}
                  className={`listsingle ${this.inchooselist(index) ? 'listsingleact' : ''}`}
                >
                  {listsingle.name}
                </View>
              )
            })}
          </View>
        </View>
      </View>
    )
  }
}

export default ChooseList
